package org.iteam.xlz.manager.timer;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import org.iteam.core.service.base.BaseParameterService;
import org.iteam.core.utils.DateUtil;
import org.iteam.xlz.core.entity.log.LogCreator;
import org.iteam.xlz.core.entity.messages.PushInfo;
import org.iteam.xlz.core.entity.messages.PushInfoRecord;
import org.iteam.xlz.core.entity.order.OrderInfo;
import org.iteam.xlz.core.entity.user.UserInfo;
import org.iteam.xlz.core.entity.user.UserRelation;
import org.iteam.xlz.core.entity.user.UserRelationRecord;
import org.iteam.xlz.core.service.LogCreatorService;
import org.iteam.xlz.core.service.message.PushInfoService;
import org.iteam.xlz.core.service.order.OrderInfoService;
import org.iteam.xlz.core.service.product.ProductSaleService;
import org.iteam.xlz.core.service.user.UserInfoService;
import org.iteam.xlz.core.service.user.UserRelationRecordService;
import org.iteam.xlz.core.service.user.UserRelationService;
import org.iteam.xlz.manager.utils.UmengDemo;

import push.android.AndroidCustomizedcast;
import push.ios.IOSCustomizedcast;

public class RelationTimerTask extends TimerTask {

	@Override
	public void run() {
		String current=DateUtil.currentTime();
		System.out.println("挖矿返现，自动完成订单定时任务开始执行。。。"+current);
		//从现在的时间开始往前推d小时，支付时间超过d小时的，订单状态为“待收货”,待完成的订单将会被拉取到
		double d=0;
			try {
				d = Double.parseDouble(BaseParameterService.getInstance().getValueByName("RELATIONRELAY")+"");
			} catch (NumberFormatException e1) {
				e1.printStackTrace();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		long delay=(long) (new Date().getTime()-60*60*1000*d);
		List<OrderInfo> list=OrderInfoService.getInstance().getRelationOrder(DateUtil.formatDateTime(new Date(delay)));
		//过滤掉不用返现的订单
		List<OrderInfo> needRelation=new ArrayList<OrderInfo>();
		List<OrderInfo> NoRelation=new ArrayList<OrderInfo>();
		for(OrderInfo o:list){
			if(o.getStatus()==0){
				OrderInfoService.getInstance().closeOrder(o);
				continue;
			}
			if(o.getOrdertype()==1||o.getOrdertype()==2){
				NoRelation.add(o);
				continue;
			}
			boolean hascommission=ProductSaleService.getInstance().findOne(o.getPpid()).getHascommission()==0;
			if(hascommission){
				needRelation.add(o);
			}else{
				NoRelation.add(o);
			}
		}
		
		//开始返现,通过订单uid找到挖矿关系记录
		int total=0;
		int m=0;
		for(OrderInfo o:needRelation){
			UserRelation relation=UserRelationService.getInstance().getOneBySubordinateuid(o.getUid());
			StringBuilder logContent=new StringBuilder("定时任务:RelationTimerTask在"+current+"对订单ID："+o.getOid()+"进行了挖矿返现操作");
			//如果relation为空则表示该用户不是矿
			if(null!=relation){
				BigDecimal orderAmount=new BigDecimal(o.getTotalprice());
				BigDecimal rate=new BigDecimal(relation.getRoyaltyrate());
				orderAmount=orderAmount.multiply(rate);
				orderAmount=orderAmount.setScale(2,BigDecimal.ROUND_HALF_UP);
				String amount=orderAmount.toString();
				
				UserRelationRecord record=new UserRelationRecord();	
				record.setAmount(amount);
				record.setOid(o.getOid());
				record.setRoyaltyrate(relation.getRoyaltyrate());
				record.setSuperioruid(relation.getSuperioruid());
				record.setSubordinateuid(relation.getSubordinateuid());
				boolean flag=UserRelationRecordService.getInstance().relate(record);
				if(flag){
					total++;
					logContent.append(",返现操作执行成功");
					
					UserInfo user=UserInfoService.getInstance().findByUid(record.getSuperioruid());
					int os=user.getOs();
					user=UserInfoService.getInstance().findByUid(record.getSubordinateuid());
					PushInfo push=PushInfoService.getInstance().findIsCurrent(1);
					String content=push.getContent();
					content=content.replace("{username}",user.getUsername());
					content=content.replace("{daole}",record.getAmount());
					
					UmengDemo demo=new UmengDemo("来自友盟的消息","您的金矿返佣啦",content,content);
					try {
						if(os==0){
							AndroidCustomizedcast acast=new AndroidCustomizedcast(demo.AndroidAppkey,demo.AndroidAppMasterSecret);
							acast.setAlias(record.getSuperioruid(),"uid");
							demo.sendAndroidCustomizedcast(acast);
						}else{
							IOSCustomizedcast icast=new IOSCustomizedcast(demo.IosAppkey,demo.IosAppMasterSecret);
							icast.setAlias(record.getSuperioruid(),"uid");
							demo.sendIOSCustomizedcast(icast);								
						}
						PushInfoRecord pir=new PushInfoRecord();
						pir.setPiid(push.getPiid());
						pir.setUid(record.getSuperioruid());
						PushInfoService.getInstance().record(pir);
						logContent.append(",友盟已推送");
					} catch (Exception e) {
						e.printStackTrace();
					}
					flag=OrderInfoService.getInstance().finishOrder(o);
					if(flag){
						m++;
						logContent.append(",订单完成执行成功");
					}else{
						logContent.append(",订单完成执行失败");
					}
				}else{
					logContent.append(",返现操作执行失败,放弃执行订单完成");
				}
			}else{
				logContent.append(",该订单的用户无挖矿关系");
				total++;
				boolean flag=OrderInfoService.getInstance().finishOrder(o);
				if(flag){
					m++;
					logContent.append(",订单完成执行成功");
				}else{
					logContent.append(",订单完成执行失败");
				}
			}
			LogCreator log=new LogCreator();
			log.setCreator("RelationTimerTask");
			log.setLogcontent(logContent.toString());
			log.setLogtype(3);
			LogCreatorService.getInstance().create(log);
		}
		
		//改所有NoRelation订单状态为已完成
		for(OrderInfo o:NoRelation){
			StringBuilder logContent=new StringBuilder("定时任务:RelationTimerTask在"+current+"对订单ID："+o.getOid()+"进行了自动完成操作");
			boolean flag=OrderInfoService.getInstance().finishOrder(o);
			if(flag){
				m++;
				logContent.append(",订单完成执行成功");
			}else{
				logContent.append(",订单完成执行失败");
			}
			LogCreator log=new LogCreator();
			log.setCreator("RelationTimerTask");
			log.setLogcontent(logContent.toString());
			log.setLogtype(3);
			LogCreatorService.getInstance().create(log);
		}
		
		System.out.println("挖矿返现，自动完成订单定时任务执行完毕,执行结果:总订单:"+list.size()+"条,返现订单:"+needRelation.size()+"条,返现执行成功:"+total+"条,自动完成订单执行成功:"+m+"条"+DateUtil.currentTime());
	}
public static void main(String[] args) {
	BigDecimal big=new BigDecimal(2.51300);
	big=big.setScale(2,BigDecimal.ROUND_HALF_UP);
	System.out.println(big.toString());
}
}
